﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Service.Core.Interface;
using Service.Core.Result;
using Tools;
using Web.Filter;
using Web.Service;
using Web.ViewModel.CoreData;
using Web.ViewModel.VersionData;
using Web.Models.CoreData;
using System.Net;
using System.Data;

namespace Web.Controllers
{
    [SysUserPermissionsFilter]
    public class BackStageController : BaseController
    {
        UserVesselService userVesselService = UserVesselService.GetInstance();
        ShipService shipService = ShipService.GetInstance();
        ReportService reportService = ReportService.GetInstance();
        SysUserService sysService = SysUserService.GetInstance();
        CompanyService companyService = CompanyService.GetInstance();
        UserService userService = UserService.GetInstance();
        ConfigsService configsService = ConfigsService.GetInstance();
        GalleryService galleryService = GalleryService.GetInstance();

        /// <summary>
        /// 补全数据，e-Navigation1.1.0.0升级使用
        /// </summary>
        /// <returns></returns>
        public String CompleteData()
        {
            try
            {
                userVesselService.InitUserVesselData();//补全用户船舶数据
                shipService.ModifyShipList();//更新所有船信息
                reportService.ModifReports();
            }
            catch (Exception ex)
            {
                return "初始化失败,错误信息：" + ex.Message;
            }
            return "初始化成功";
        }

        public ActionResult Monitor()
        {
            return View();
        }


        // GET: BackStage
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(String account, String password)
        {
            var result = sysService.Login(account, password);
            if ((ResultType)result.GetCode() == ResultType.ParamIsNull)
            {
                ViewData["LoginInfo"] = "请输入帐号或密码";
            }
            else if ((ResultType)result.GetCode() == ResultType.AccountLoginFaile)
            {
                ViewData["LoginInfo"] = "您的帐号或者密码错误，请重新输入";
            }
            else if ((ResultType)result.GetCode() == ResultType.Success)
            {
                return RedirectToAction("UserList", "BackStage");
            }
            return View();
        }


        #region 系统用户管理


        public ActionResult SysUserList()
        {
            ViewData["Data"] = sysService.GetAllSysUser();
            return View();
        }

        [HttpGet]
        public ActionResult AddSysUser()
        {
            return View();
        }

        [HttpPost]
        public ActionResult AddSysUser(SysUserModel model)
        {
            var result = sysService.AddSysUser(model);
            if ((ResultType)result.GetCode() == ResultType.Success)
            {
                ViewData["BackMsg"] = "添加成功";
            }
            else
            {
                ViewData["BackMsg"] = result.GetMsg();
            }
            return View();
        }

        public String ResetPassword(Guid id)
        {

            return JsonHelper.SerializeObject(sysService.ResetPassword(id));
        }



        #endregion

        #region 用户管理

        #region 公司用户管理

        /// <summary>
        /// 公司列表
        /// </summary>
        /// <returns></returns>
        public ActionResult CompanyList()
        {
            ViewData["Data"] = companyService.GetAllCompany();
            return View();
        }

        /// <summary>
        /// 添加公司用户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult AddCompany(String id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                ViewData["Data"] = companyService.QueryCompanyModel(id);
            }
            return View();
        }
        /// <summary>
        /// 添加公司用户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddCompany(CompanyModel model)
        {
            var result = companyService.UpdateCompany(model);
            if ((ResultType)result.GetCode() == ResultType.Success)
            {
                ViewData["BackMsg"] = "操作成功";
                return RedirectToAction("CompanyList");
            }
            else
            {
                ViewData["BackMsg"] = result.GetMsg();
            }
            return View();
        }

        /// <summary>
        /// 上传公司logo图片
        /// </summary>
        /// <returns></returns>
        public String UploadLogo(string companyId)
        {
            try
            {
                var files = Request.Files;
                if (files != null && files.Count > 0)
                {
                    HttpPostedFileBase file = files[0];
                    string filepath = Server.MapPath("/") + "UpLoad\\Logo";
                    if (!Directory.Exists(filepath))
                    {
                        Directory.CreateDirectory(filepath);
                    }
                    string filename = Path.Combine(filepath, companyId + "." + file.FileName.Split('.')[1]);
                    file.SaveAs(filename);
                    var result = companyService.UploadLogo(companyId, filename.Replace(Server.MapPath("/"), "\\"));
                    if ((ResultType)result.GetCode() == ResultType.Success)
                    {
                        return "{\"error\": \"上传成功\"}";
                    }
                    else
                    {
                        return "{\"error\": \"上传失败，请尝试刷新页面再次操作\"}";
                    }
                }
                return "{\"error\": \"请选择文件\"}";
            }
            catch (Exception ex)
            {
                return "{\"error\": \"" + ex.Message + "\"}";
            }
        }

        /// <summary>
        /// 设置公司下所有用户所有船舶的有效时间
        /// </summary>
        /// <param name="companyId"></param>
        /// <param name="datetime"></param>
        /// <returns></returns>
        public String SetCompanyExpirationDate(String companyId, DateTime expirationDate)
        {
            return JsonResult(userVesselService.SetCompanyExpirationDate(companyId, expirationDate));
        }

        /// <summary>
        /// 设置用户所有船舶的有效时间
        /// </summary>
        /// <param name="companyId"></param>
        /// <param name="datetime"></param>
        /// <returns></returns>
        public String SetUserExpirationDate(String userId, DateTime expirationDate)
        {
            return JsonResult(userVesselService.SetUserExpirationDate(userId, expirationDate));
        }


        #endregion

        #region 终端管理

        /// <summary>
        /// 终端列表
        /// </summary>
        /// <returns></returns>
        public ActionResult UserList()
        {
            ViewData["Data"] = userService.GetAllUser();
            return View();
        }
        /// <summary>
        /// 添加或更新终端信息
        /// </summary>
        /// <param name="id">终端id</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult AddUser(String id)
        {
            if (!String.IsNullOrEmpty(id))
            {
                ViewData["Data"] = userService.GetUserDetail(id);
                ViewData["ShipData"] = shipService.GetUserShipModels(id);
            }
            ViewData["Company"] = companyService.GetAllCompany();
            ViewData["User"] = userService.GetAllUser();
            ViewData["Configs"] = configsService.QueryAll();
            return View();
        }

        /// <summary>
        /// 导入excel
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public String Import()
        {
            try
            {
                var files = Request.Files;
                if (files != null && files.Count > 0)
                {
                    HttpPostedFileBase file = files[0];
                    if (!file.FileName.ToLower().Contains("xls") && !file.FileName.ToLower().Contains("xlsx"))
                    {
                        return "{\"error\": \"上传失败，只支持上传xls或xlsx格式文件\"}";
                    }
                    string filepath =Path.Combine(Server.MapPath("/"), "UpLoad","xls",file.FileName);
                    file.SaveAs(filepath);
                    DataTable dt = OfficeHelper.InputExl(new FileStream(filepath, FileMode.Open, FileAccess.Read)).FirstOrDefault();
                    var mmsiCol = 0;
                    List<string> mmsis = new List<string>();
                    foreach (DataRow dr in dt.Rows)
                    {
                        for (int i = 0; i < dt.Columns.Count; i++)
                        {
                            if (mmsiCol != 0)
                            {
                                mmsis.Add(dr[mmsiCol].ToString());
                                break;
                            }
                            else
                            {
                                string val = dr[i].ToString();
                                long a;
                                if (val.Length == 9 && long.TryParse(val, out a))
                                {
                                    mmsis.Add(val);
                                    mmsiCol = i;
                                    break;
                                }
                            }
                        }
                    }
                    if (mmsis.Count>0)
                    {
                        return "{\"Data\": \""+string.Join(",",mmsis.ToArray())+"\"}";
                    }
                    else
                    {
                        return "{\"error\": \"上传失败，请尝试刷新页面再次操作\"}";
                    }
                }
                return "{\"error\": \"请选择文件\"}";
            }
            catch (Exception ex)
            {
                return "{\"error\": \"" + ex.Message + "\"}";
            }
        }




        /// <summary>
        /// 更新终端信息
        /// </summary>
        /// <param name="user">终端信息</param>
        /// <param name="company">用户信息</param>
        /// <returns></returns>
        public String ModifyUser(UserModel user, CompanyModel company)
        {
            return JsonResult(userService.ModifUser(user, company));
        }



        /// <summary>
        /// 检查MMSI的信息
        /// </summary>
        /// <param name="MMSI">mmsi集</param>
        /// <returns></returns>
        public String ValidateMMSI(string MMSI)
        {
            var result = shipService.QueryShipDetail(MMSI);
            return JsonResult(result);
        }


        #endregion

        #region 配置管理

        /// <summary>
        /// 用户配置项列表
        /// </summary>
        /// <param name="id">用户id（companyId）</param>
        /// <returns></returns>
        public ActionResult Configs(String companyId)
        {
            ViewData["Data"] = configsService.QueryConfigs(companyId);
            return View();
        }

        /// <summary>
        /// 读取配置文件
        /// </summary>
        /// <param name="path">文件相对路径,例:/Upload/Config.xml</param>
        /// <returns></returns>
        public String ReadConfig(String path)
        {
            return JsonResult(configsService.ReadConfig(Server.MapPath("~") + path));
        }



        /// <summary>
        /// 添加配置项
        /// </summary>
        /// <param name="name">配置项名称</param>
        /// <param name="id">用户id（companyId）</param>
        /// <returns></returns>
        public String AddConfig(String name, String id)
        {
            return JsonResult(configsService.AddConfig(name, id));
        }

        /// <summary>
        /// 更新配置项
        /// </summary>
        /// <param name="name">配置项名称</param>
        /// <param name="id">用户id（companyId）</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult ModifConfigs(Configs configs, String content)
        {
            configsService.ModifConfigs(configs, content);
            return RedirectToAction("Configs", new { companyId = configs.CompanyId });
        }


        /// <summary>
        /// 删除配置项
        /// </summary>
        /// <param name="id">配置项id</param>
        /// <returns></returns>
        public String DeleteConfigs(String id)
        {
            return JsonResult(configsService.DeleteConfigs(id));
        }

        /// <summary>
        /// 下载配置文件
        /// </summary>
        /// <param name="id">配置文件id</param>
        /// <returns></returns>
        public string DownloadConfig(String id)
        {
            IServiceResult result = configsService.DownLoadConfig(id);
            return JsonResult(result);
        }

        #endregion

        #region 图库管理

        /// <summary>
        /// 所有用户图库
        /// </summary>
        /// <returns></returns>
        public ActionResult Gallery()
        {
            ViewData["Gallery"] = galleryService.QueryAll();
            ViewData["Data"] = companyService.GetAllCompany();
            return View();
        }

        /// <summary>
        /// 更新图片信息
        /// </summary>
        /// <param name="gallery">图片值内容</param>
        /// <returns></returns>
        public String ModifyImage(Gallery gallery)
        {
            IServiceResult result = galleryService.ModifyImage(gallery);
            if ((ResultType)result.GetCode() == ResultType.Success)
            {
                HttpCookie cookie = Request.Cookies["fileId"];
                if (cookie != null)
                {
                    cookie.Value = null;
                    HttpContext.Response.Cookies.Add(cookie);
                }
            }
            return JsonResult(result);
        }

        /// <summary>
        /// 删除图片
        /// </summary>
        /// <param name="id">图片id</param>
        /// <returns></returns>
        public String DeleteImage(String id)
        {
            return JsonResult(galleryService.DeleteImage(id));
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <returns></returns>
        public String UploadImg()
        {
            try
            {
                String companyId = Request.Cookies["companyId"].Value;
                var id = Guid.NewGuid().ToString();
                var fileId = new HttpCookie("fileId", id);
                HttpContext.Response.Cookies.Add(fileId);
                var files = Request.Files;
                if (files != null && files.Count > 0)
                {
                    HttpPostedFileBase file = files[0];
                    string filepath = Server.MapPath("/") + "UpLoad\\Gallery\\" + companyId;
                    if (!Directory.Exists(filepath))
                    {
                        Directory.CreateDirectory(filepath);
                    }
                    string filename = Path.Combine(filepath, id + "." + file.FileName.Split('.')[1]);
                    file.SaveAs(filename);
                    var result = galleryService.UploadUserImg(companyId, filename.Replace(Server.MapPath("/"), "\\"), id);
                    if ((ResultType)result.GetCode() == ResultType.Success)
                    {
                        return "{\"error\": \"上传成功\"}";
                    }
                    else
                    {
                        return "{\"error\": \"上传失败，请尝试刷新页面再次操作\"}";
                    }
                }
                return "{\"error\": \"请选择文件\"}";
            }
            catch (Exception ex)
            {
                return "{\"error\": \"" + ex.Message + "\"}";
            }
        }

        /// <summary>
        /// 下载配置文件
        /// </summary>
        /// <param name="id">配置文件id</param>
        /// <returns></returns>
        public string DownloadImages(List<string> filenames)
        {
            IServiceResult result = galleryService.DownLoadImage(filenames);
            return JsonResult(result);
        }

        #endregion

        #endregion


        #region 船舶管理



        #endregion

        #region 版本控制管理

        #region 版本库管理
        /// <summary>
        /// 版本库列表
        /// </summary>
        /// <returns></returns>
        public ActionResult VersionLibList()
        {
            return View(VersionService.GetInstance().GetAllVersionLib());
        }

        /// <summary>
        /// 修改版本库信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public String UpdateVersionLib(VersionLibModel model)
        {
            return JsonResult(VersionService.GetInstance().ModifyVersionLib(model));
        }



        /// <summary>
        /// 获取版本库信息
        /// </summary>
        /// <param name="shortName"></param>
        /// <returns></returns>
        public String GetVersionLib(Guid id)
        {
            return JsonResult(VersionService.GetInstance().GetVersionLib(id));

        }

        /// <summary>
        /// 版本列表
        /// </summary>
        /// <param name="libId">版本库ID</param>
        /// <returns></returns>
        public ActionResult VersionList(String libId)
        {
            return View();
        }



        #endregion

        #endregion
    }
}